﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

using log4net;
using log4net.Config;
using log4net.Util;


namespace IsmlTools.Common
{
    public class WebHelper
    {
        private ILog log = LogManager.GetLogger(typeof(WebHelper));

        public string DownloadFile(string pageLink)
        {
            using (WebClient webclient = new WebClient())
            {
                Uri uri = new Uri(pageLink);

                string filename = Application.StartupPath + (pageLink.Replace("http:/", string.Empty)).Replace("/", @"\");
                string pathname = Path.GetDirectoryName(filename);
                if (pathname != null && !Directory.Exists(pathname))
                    Directory.CreateDirectory(pathname);
                if (File.Exists(filename))
                    return filename;
                    //File.Move(filename, filename + "_" + DateTime.Now.ToString("yyyyMMddHHmmssffff"));

                try
                {
                    webclient.DownloadFile(uri, filename);
                }
                catch (WebException ex)
                {
                    log.ErrorFormat("DownloadFile() failed. pageLink: " + pageLink + " Details: " + ex.GetBaseException().Message);
                    return string.Empty;
                }

                return filename;
            }
        }

        public string ReadPage(string pageLink)
        {
            //pageLink = @"http://archive.internationalsaimoe.com/visuals/maps/2013/Map_p5-1.gif";
            string filename = DownloadFile(pageLink);
            //using (Stream stream = new Stream(pageLink)) {

            try
            {
                using (StreamReader streamreader = new StreamReader(filename))
                {
                    return streamreader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                log.ErrorFormat("ReadPage() failed. pageLink: " + pageLink + " Details: " + ex.GetBaseException().Message);
                return string.Empty;
            }
        }
    }
}
